import { defineStore } from 'pinia';
import { ref } from 'vue';
import { $fetch } from '@/settings/utils/fetch';
import i18n from '@/settings/i18n';

export interface SiteConfig {
  name: string,
  description: string,
  logo: string,
  headLogo: string,
  seo: {
    title: string,
    description: string,
    keywords: string,
  },
}

const useAppStore = defineStore('app', () => {
  const theme = ref('light');
  const hideMenu = ref(false);
  const menuCollapse = ref(false);
  const device = ref('desktop');
  const config = ref<SiteConfig>({
    name: '',
    description: '',
    logo: '',
    headLogo: '',
    seo: {
      title: '',
      description: '',
      keywords: '',
    },
  });

  // Change theme color
  const toggleTheme = (dark: boolean) => {
    if (dark) {
      theme.value = 'dark';
      document.querySelector('html')?.setAttribute('arco-theme', 'dark');
      document.querySelector('body')?.setAttribute('arco-theme', 'dark');
    }
    else {
      theme.value = 'light';
      document.querySelector('html')?.removeAttribute('arco-theme');
      document.querySelector('body')?.removeAttribute('arco-theme');
    }
  }

  const toggleDevice = (newDevice: string) => {
    device.value = newDevice;
  }

  const toggleMenu = (value: boolean) => {
    hideMenu.value = value;
  }

  const fetchConfig = async () => {
    const { isSuccess, data } = await $fetch('/community/getCommunityInfo');

    if (isSuccess) {
      config.value = {
        name: data.communityName,
        description: data.commIllustrate,
        logo: data.communityLogo,
        headLogo: data.communityHeadPic,
        seo: {
          title: data.commTitle,
          description: data.commDesc,
          keywords: data.commKeywords,
        },
      };
    }

    return { isSuccess };
  }

  const setWindowTitle = (title?: string) => {
    window.document.title = (title ? `${title} - ` : '') + `${i18n.global.t('settings.websiteTitle.default')} - ${config.value.seo.title || config.value.name}`;
  }

  return {
    theme,
    hideMenu,
    menuCollapse,
    device,
    toggleTheme,
    toggleDevice,
    toggleMenu,
    fetchConfig,
    config,
    setWindowTitle,
  };
});

export default useAppStore;
